package org.csu.newpetstoreback.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.csu.newpetstoreback.common.CommonResponse;
import org.csu.newpetstoreback.entity.Comment;
import org.csu.newpetstoreback.entity.OrderItem;
import org.csu.newpetstoreback.persistence.CommentMapper;
import org.csu.newpetstoreback.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("commentService")
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    //获取某item的所有评论
    @Override
    public CommonResponse<List<Comment>> getCommentsByItemid(String itemId) {

        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("itemId", itemId);
        List<Comment> commentList = commentMapper.selectList(queryWrapper);

        if(commentList.isEmpty()){
            return CommonResponse.createForNotFound("没有该单品的评论信息");
        }else {
            return CommonResponse.createForSuccess(commentList);
        }
    }

    //获取某用户的所有评论
    @Override
    public CommonResponse<List<Comment>> getCommentsByUsername(String username) {

        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        List<Comment> commentList = commentMapper.selectList(queryWrapper);

        if(commentList.isEmpty()){
            return CommonResponse.createForNotFound("没有该用户的评论信息");
        }else {
            return CommonResponse.createForSuccess(commentList);
        }
    }

    //新增一条评论
    @Override
    public CommonResponse<Comment> addComment(Comment comment) {

        int addCommentSuccess = commentMapper.insert(comment);

        if (addCommentSuccess > 0){
            return CommonResponse.createForSuccessMessage("评论添加成功");
        }else {
            return CommonResponse.createForUnauthorized("评论添加失败");
        }
    }

    //删除指定评论
    @Override
    public CommonResponse<Comment> deleteCommentById(int commentId) {

        int deleteCommentSuccess = commentMapper.deleteById(commentId);

        if(deleteCommentSuccess > 0){
            return CommonResponse.createForSuccessMessage("评论删除成功");

        }else {
            return CommonResponse.createForNotFound("没有该评论的信息，无法删除");
        }
    }

    @Override
    public int getCommentNum() {

        Comment commentMax = commentMapper.selectOne(new QueryWrapper<Comment>().orderByDesc("commentId").last("limit 1"));

        int commentNum = commentMax.getCommentId();

        return commentNum;
    }
}
